package com.alipay.util;

import org.junit.Test;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;


/**
 * FTP工具类
 *
 * 支付宝沙盒：https://docs.open.alipay.com/200/105311/
 */
public class alipay {
		//支付宝连接器
	   private AlipayClient alipayClient;
	   //支付宝退款请求
	   private AlipayTradeRefundRequest request;

		//阿里退款地址，支付宝网关
	   private String alipayUrl="https://openapi.alipaydev.com/gateway.do";//"https://openapi.alipay.com/gateway.do"正式环境
	   //退款APP的APPID
	   private String appId="2016092600598676";
	   //加密后私钥
	   private String privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZDCopqU7EGXGWMXA8KLmlT+K1HUlfqQUko7DWbwR8py+pUCHZoXr4EUA3B1UJ5RPom1Xr39SAVZgat2Vx0iP/KP9CrPcu10z5tDijwWbJFl0XFWYavoCokeDF6auUS0ewY6y1/kcYz0nB1tnx7ZOEmUGjxQOlVu/00FNeYRI6hcKXU0EhE6JFyZq8h0xInHRjrTdJszSM+S55z6PDe5beuByzoeU23OHlmebkIQvBPIcdeZ+9dSlc33T3w0UntrtXPm+wGHxRsWE4QOMGZ7D2HR0sTVZogVEQ6a8LsW/4ayURqGDjveaSxqPBX4YIkSYw3dqTFg4MH1TK03QeSobJAgMBAAECggEBAIsOjHiSBqkSXSwT+2ANuK/FJ71bwMET90JVIGWVNUR1O07hKgBtQieGtQvKs69r3mzoRmcsVg3Mt4j+vUNvpZk/DL7uHSEIKj5vS08ueE+Y7Df/D2iZUpjXAp2QNH9m7toLlm89fCfEn8Vpi1jPfctq3EMKzMc7eIa9iiIknMViO1vGu7LEERZouDHRNMccsWV7KxUaW02EBUicFQrVOz3jSvwJhMtLiMj4epLXLr4MwKxAiI8QZDSG/6DhQzQhiwYQHtYIt9dc+uWIe0cC7XkViZw0LsSl1u26GJrJ3o301+kfTLRq2TfG8zU9DzjKFb/3cy89PEKlMW6MtYmrpwECgYEA51AhHCsQugWOg6EgGSh1O3Rbrx6TzPjzOmibxLRudCMO7BCCMDiajAZcS1L4JMHXbUX4OmWzCtwAxXRUvSufkFGeZIoMuoxIg0l5DbbRV9IboXBu6CA7m4K5tG6gyyeeNUfono3fYIh3QYQRRBZKB+oDBxVpSlgwuyAAZxdBzHkCgYEAqWGv6CEmh/Awbytj3pxQ+VlVkhtmDBm2yNchvSJagPMO3Lyorzhdm/STkVrld4gGjMWxZ+PA1SEc64xEX3aN4ZFNGX11iO91+nXCyFImE67Jw0PYQvXEocW6iDVFkdte3FAYAVQXXoCN8zUlCPCPpLZjVEztwwqSYdSWEhlRWNECgYAQZQCDw5Wi6aPpNnFU9yYf+aZJ6ivlmjt7B1ELBxLRDm8PUjg3/LsPc5/1AsNtr4N6TjxCv1SKT3+Kfy1GXyInE3HbhGFUk37MN1fqHewGgnDM53Ak6avv4LsSy8h/vaYb9qXJHxsW93UkYpzqq33Bw9dFGEJnL4r8qE7+/4n9WQKBgE/AyVzZTxUuyP9vRMTqgU4G/D2hXPlRmjkS4rX1WPvidhsFUb+/IIRwMpN8YxNXHw5lf1TVblRsFPvrvb3dSoztJ4pbAl6JsdlOXXqJA5i88g9ZAJj2s7EgMuYzfyBgVFgT9lmZyK8chLoBSgDdlCUQI9Drr//oGGir+kVnWmAhAoGBANJ9dkML6YfU7WmuEMNHtXKGZDtNXEhUGUl3KwJ3C5jozdYvvXHBU/xSBedLq402C8kIbFbLbAzrbxv2IzsYDVKFvsHCrvtwnmBm6XSOeoxBdVkxlzU6XRUla1NI5ViY37bWL9+SWYonLZRPU+R+Ly4F3m8ULH+JaM3EdFt2MM0A";
	   //请求头类型 json
	   private String requestType="json";
	   //请求编码格式 GBK
	   private String requestCharacterCode="GBK";
	   //RSA2(SHA256)密钥 加密密钥
	   private String alipayPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4mMCWIjfOBE7UnAZ25U4bGYxydkxcU3BQ4YBP0DBXkvvFSb+9gG0rwfIeEWEdWugmFs7j++w1bev+UQ290AkYXwNyVeJqED/QyPfu6kKThiowP2TTVqVksjE+EZVpEX37f+eeB6MN0Nx2MS2UvliAu/4d55C+tZpkcT1VzezZFOf0yTHU0lkDkHqZZ4pwXrQRTH1kttt2PMe2zYAlgSNs37OANCumOfugnahXl4Ne86AhSNP7Zz5H4/2jRN6kQP8PDSkm9wwLE3O5YEtO3sF1ULr8JtsfZenNMsePZA6d4/j1kUWTf4qGGBrQnL9sfYxwt+6JTcAwaEg9Uz4YYFXxwIDAQAB";
	   //加密类型 加密类型
	   private String EncryptionType="RSA2";

	   //支付及退款条形码号码
	   private String out_trade_no = "21312314123";
	   //订单号
	   private String trade_no = "2019031422001437340500543504";
	   //退款金额
	   private double refund_amount = 0.01;

    public static void main(String[] args) {
    	try {
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
			AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
			request.setBizContent("{" +
			"\"out_trade_no\":\"20150320010101001\"," +
			"\"trade_no\":\"2014112611001004680073956707\"," +
			"\"refund_amount\":200.12," +
			"\"refund_currency\":\"USD\"," +
			"\"refund_reason\":\"正常退款\"," +
			"\"out_request_no\":\"HZ01RF001\"," +
			"\"operator_id\":\"OP001\"," +
			"\"store_id\":\"NJ_S_001\"," +
			"\"terminal_id\":\"NJ_T_001\"," +
			"      \"goods_detail\":[{" +
			"        \"goods_id\":\"apple-01\"," +
			"\"alipay_goods_id\":\"20010001\"," +
			"\"goods_name\":\"ipad\"," +
			"\"quantity\":1," +
			"\"price\":2000," +
			"\"goods_category\":\"34543238\"," +
			"\"categories_tree\":\"124868003|126232002|126252004\"," +
			"\"body\":\"特价手机\"," +
			"\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
			"        }]," +
			"      \"refund_royalty_parameters\":[{" +
			"        \"royalty_type\":\"transfer\"," +
			"\"trans_out\":\"2088101126765726\"," +
			"\"trans_out_type\":\"userId\"," +
			"\"trans_in_type\":\"userId\"," +
			"\"trans_in\":\"2088101126708402\"," +
			"\"amount\":0.1," +
			"\"amount_percentage\":100," +
			"\"desc\":\"分账给2088101126708402\"" +
			"        }]," +
			"\"org_pid\":\"2088101117952222\"" +
			"  }");
			AlipayTradeRefundResponse response = alipayClient.execute(request);
			if(response.isSuccess()){
				System.out.println("调用成功");
			} else {
				System.out.println("调用失败");
			}
		} catch (AlipayApiException ex) {
//			logger.error(ex.getMessage(), ex);
		}
    }

	/**
	 * @ alipayRefundRequest ＜支付宝退款请求＞
	 * @param out_trade_no 订单支付时传入的商户订单号,不能和 trade_no同时为空。
	 * @param trade_no 支付宝交易号，和商户订单号不能同时为空
	 * @param refund_amount 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
	 * @return
	 */
    @Test
	public void alipayRefundRequest(){

		// 发送请求
		String strResponse = null;
		try {
//			alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do","2016092600598676","MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZDCopqU7EGXGWMXA8KLmlT+K1HUlfqQUko7DWbwR8py+pUCHZoXr4EUA3B1UJ5RPom1Xr39SAVZgat2Vx0iP/KP9CrPcu10z5tDijwWbJFl0XFWYavoCokeDF6auUS0ewY6y1/kcYz0nB1tnx7ZOEmUGjxQOlVu/00FNeYRI6hcKXU0EhE6JFyZq8h0xInHRjrTdJszSM+S55z6PDe5beuByzoeU23OHlmebkIQvBPIcdeZ+9dSlc33T3w0UntrtXPm+wGHxRsWE4QOMGZ7D2HR0sTVZogVEQ6a8LsW/4ayURqGDjveaSxqPBX4YIkSYw3dqTFg4MH1TK03QeSobJAgMBAAECggEBAIsOjHiSBqkSXSwT+2ANuK/FJ71bwMET90JVIGWVNUR1O07hKgBtQieGtQvKs69r3mzoRmcsVg3Mt4j+vUNvpZ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xBdVkxlzU6XRUla1NI5ViY37bWL9+SWYonLZRPU+R+Ly4F3m8ULH+JaM3EdFt2MM0A"
//					,"json","GBK","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4mMCWIjfOBE7UnAZ25U4bGYxydkxcU3BQ4YBP0DBXkvvFSb+9gG0rwfIeEWEdWugmFs7j++w1bev+UQ290AkYXwNyVeJqED/QyPfu6kKThiowP2TTVqVksjE+EZVpEX37f+eeB6MN0Nx2MS2UvliAu/4d55C+tZpkcT1VzezZFOf0yTHU0lkDkHqZZ4pwXrQRTH1kttt2PMe2zYAlgSNs37OANCumOfugnahXl4Ne86AhSNP7Zz5H4/2jRN6kQP8PDSkm9wwLE3O5YEtO3sF1ULr8JtsfZenNMsePZA6d4/j1kUWTf4qGGBrQnL9sfYxwt+6JTcAwaEg9Uz4YYFXxwIDAQAB","RSA2");
			alipayClient = new DefaultAlipayClient(alipayUrl,appId,privateKey,requestType,requestCharacterCode,alipayPublicKey,EncryptionType);
			request = new AlipayTradeRefundRequest();
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"out_trade_no\":\"" + out_trade_no + "\","); //商户订单号
			sb.append("\"trade_no\":\"" + trade_no + "\",");//支付宝交易号
			sb.append("\"refund_amount\":" + refund_amount);//退款的金额   + ","
//			sb.append("\"refund_currency\":\"USD\","                                  );
//			sb.append("\"refund_reason\":\"正常退款\","                                 );
//			sb.append("\"out_request_no\":\"HZ01RF001\","                             );
//			sb.append("\"operator_id\":\"OP001\","                                    );
//			sb.append("\"store_id\":\"NJ_S_001\","                                    );
//			sb.append("\"terminal_id\":\"NJ_T_001\","                                 );
//			sb.append("\"goods_detail\":[{"                                     );
//			sb.append("\"goods_id\":\"apple-01\","                            );
//			sb.append("\"alipay_goods_id\":\"20010001\","                             );
//			sb.append("\"goods_name\":\"ipad\","                                      );
//			sb.append("\"quantity\":1,"                                               );
//			sb.append("\"price\":2000,"                                               );
//			sb.append("\"goods_category\":\"34543238\","                              );
//			sb.append("\"categories_tree\":\"124868003|126232002|126252004\","        );
//			sb.append("\"body\":\"特价手机\","                                          );
//			sb.append("\"show_url\":\"http://www.alipay.com/xxx.jpg\""                );
//			sb.append("}],"                                                   );
//			sb.append("\"refund_royalty_parameters\":[{"                        );
//			sb.append("\"royalty_type\":\"transfer\","                        );
//			sb.append("\"trans_out\":\"2088101126765726\","                           );
//			sb.append("\"trans_out_type\":\"userId\","                                );
//			sb.append("\"trans_in_type\":\"userId\","                                 );
//			sb.append("\"trans_in\":\"2088101126708402\","                            );
//			sb.append("\"amount\":0.1,"                                               );
//			sb.append("\"amount_percentage\":100,"                                    );
//			sb.append("\"desc\":\"分账给2088101126708402\""                            );
//			sb.append("}],"                                                   );
//			sb.append("\"org_pid\":\"2088101117952222\""                              );
			sb.append("}");
			request.setBizContent(sb.toString());
			AlipayTradeRefundResponse response = alipayClient.execute(request);
			strResponse=response.getCode();
			if ("10000".equals(response.getCode())) {
				strResponse="退款成功";
			}else {
				strResponse=response.getSubMsg();
			}
		} catch (Exception ex) {
//			logger.error(ex.getMessage(), ex);
		}
//	 	return strResponse;
	}
}